package br.elsa.survey.view.beans.managed;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;

import br.elsa.survey.dao.exceptions.DataNotFoundException;
import br.elsa.survey.domain.qualifiers.NewEntity;
import br.elsa.survey.domain.questions.Question;
import br.elsa.survey.domain.survey.Survey;
import br.elsa.survey.domain.survey.SurveyFactory;
import br.elsa.survey.services.QuestionService;
import br.elsa.survey.services.SurveyService;
import br.elsa.survey.view.messages.ViewMessages;

@ViewScoped
@ManagedBean
public class SurveyCreationView {

	public List<Question> questions = null;
	
	@EJB
	private QuestionService questionService;
	
	@EJB
	private SurveyService surveyService;
	
	@Inject
	private ViewMessages viewMessages;
	
	@Inject
	private SurveyFactory surveyFactory;
	
	@Inject @NewEntity
	private Survey newSurvey;
	
	public SurveyCreationView() {
		
	}
	
	public SurveyCreationView(SurveyService surveyService, QuestionService questionService, ViewMessages viewMessages, List<Question> questions, Survey newSurvey, SurveyFactory surveyFactory) {
		
		this.surveyService = surveyService;
		this.questionService = questionService;
		this.viewMessages = viewMessages;
		this.questions = questions;
		this.newSurvey = newSurvey;
		this.surveyFactory = surveyFactory;
	}

	@PostConstruct
	public void loadQuestions() {
		
		try {
			this.questions = questionService.getAllQuestions();
			
		} catch (DataNotFoundException e) {
			viewMessages.addWarnMessage("There is no question registered in the system");
			questions = null;
		}
	}
	
	public void createSurvey() {
		
		surveyService.create(newSurvey);
		viewMessages.addInfoMessage("New survey created");
		
		resetViewState();
	}
	
	public void resetViewState() {
		
		this.newSurvey = surveyFactory.createSurvey();
		loadQuestions();
	}
	
	public void selectQuestion(Question question) {
		
		this.newSurvey.addQuestion(question);
		this.questions.remove(question);
	}
	
	public void removeQuestion(Question question) {
		
		this.newSurvey.removeQuestion(question);
		this.questions.add(question);
	}

	public List<Question> getQuestions() {
		
		return questions;
	}

	public Survey getNewSurvey() {
		return newSurvey;
	}

}
